// time.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <Windows.h>
#include <list>
using namespace std;
int box[8][10]={{1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,1,0,1,0,1,1,1,1,1},
{1,0,1,0,0,0,0,0,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,1,0,0,1,1,0,0,0,1},
{1,0,1,1,0,0,1,1,0,1},
{1,1,1,1,1,1,1,1,1,1}};
struct sPoint
{
sPoint(int x1,int y1){x=x1;y=y1;}
int x;
int y;
};
void calc(int *box,int width,int height,sPoint start,sPoint end)
{
list<sPoint> s;
box[start.x*width+start.y]=2;
int x=start.x,y=start.y;
s.push_back(sPoint(x,y));
while(1)
{
if(x==end.x && y==end.y)
{
while (!s.empty())
{
cout<<s.front().x<<" "<<s.front().y<<endl;
s.pop_front();
}
break;
}
else
{
//cout<<x<<" "<<y<<endl;
}
bool bGo=false;
for(int i=0;i<8;i++)
{
switch(i)
{
case 0:
{
if(y>0 && box[(y-1)*width+x]==0)
{
y=y-1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
case 1:
{
if(x<width-1 && y>0 && box[(y-1)*width+x+1]==0)
{
x=x+1;
y=y-1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
case 2:
{
if(x<width-1 && box[y*width+x+1]==0)
{
x=x+1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
case 3:
{
if(x<width-1 && y<height-1 && box[(y+1)*width+x+1]==0)
{
x=x+1;
y=y+1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
case 4:
{
if(y<height-1 && box[(y+1)*width+x]==0)
{
y=y+1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
case 5:
{
if(x>0 && y<height-1 && box[(y+1)*width+x-1]==0)
{
x=x-1;
y=y+1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
case 6:
{
if(x>0 && box[y*width+x-1]==0)
{
x=x-1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
case 7:
{
if(x>0 && y>0 && box[(y-1)*width+x-1]==0)
{
x=x-1;
y=y-1;
box[y*width+x]=2;
s.push_back(sPoint(x,y));
bGo=true;
}
break;
}
}
if(bGo)
{
break;
}
}
if(!bGo)
{
if(s.size()>0)
{
sPoint p=s.back();
s.pop_back();
x=p.x;
y=p.y;
}else
{
cout<<"error"<<endl;
break;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
calc((int*)box,10,8,sPoint(1,1),sPoint(8,6));
return 0;
}
c++解决迷宫寻路问题
最新推荐文章于 2023-07-15 10:34:41 发布